# -- coding:utf-8 --
import requests

class getdm:

    def __init__(self,roomid,howdm,rundef):#roomid房间号，howdm保留多少条，rundef传入一个def
        self.url = r'https://api.live.bilibili.com/ajax/msg'
        self.form ={'roomid': roomid,'csrf_token' : '8555f03a84aaf5c5599091cdc7959e0c'}
        self.howdm = howdm
        self.alldm =[]
        self.rundef = rundef

    def writedm(self,dm):#有新弹幕时执行
        f = open ('dm.txt', 'a',encoding='utf-16')
        f.write(str(dm))
        f.write('\n')
        f.close
        self.rundef(dm)#执行的rundef传入弹幕的dic

    def newalldm(self):#获得弹幕
        html = requests.post(self.url,data=self.form)#获得弹幕的json
        for dm in html.json()['data']['room']:
            if dm not in self.alldm:
                self.alldm.append(dm)
                self.writedm(dm)
            if len(self.alldm)  >self.howdm:
                self.alldm.pop(0)


if __name__ == '__main__':

    def rundef(dm):
        print(dm['text'])

    getdmtest = getdm(47631,10,rundef)
    while True:
        getdmtest.newalldm()
